<?php

namespace app\admin\model\wanlshop;

use think\Model;
use app\admin\model\User;
use traits\model\SoftDelete;

class Share extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'wanlshop_share';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'created_at',
        'status_text',
        'inv_code',
        'parent_name',
        'parent_code',
    ];

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }

    public function getLevelList()
    {
        return ['1' => __('Level 1'), '2' => __('Level 2')];
    }

    public function getAudittimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audittime']) ? $data['audittime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setAudittimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function getInvCodeAttr()
    {
        return self::where('id', $this->parent_id)->value('code');
    }

    public function getCreatedAtAttr()
    {
        return date('Y-m-d H:i:s', $this->createtime);
    }

    public function getParentNameAttr()
    {
        return self::where('id', $this->parent_id)->value('realname');
    }

    public function getParentCodeAttr()
    {
        return self::where('id', $this->parent_id)->value('code');
    }
}
